/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-08 19:48:22
 * @LastEditTime: 2022-11-03 23:40:39
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 任务请求接口
 */
import { QueryKey, useMutation, useQuery } from "react-query";
import { useHttp } from ".";
import { SortParam } from "../types/sort-param";
import { Task } from "../types/task";
import { cleanObject } from "../utils";
import {
  useOptimisticAddConfig,
  useOptimisticDeleteConfig,
  useOptimisticSortConfig,
  useOptimisticUpdateConfig,
} from "../utils/use-optimistic-options";

/**
 * @description: 任务列表查询
 * @param {QueryKey} queryKey - 查询请求缓存的值
 * @param {Partial} param - 请求的参数
 * @return {*}
 */
export const useQueryTask = (queryKey: QueryKey, param?: Partial<Task>) => {
  const client = useHttp();
  const data = cleanObject(param || {});
  return useQuery<Task[]>(queryKey, () =>
    client("/task", {
      data,
      method: "POST",
    })
  );
};

/**
 * @description: 添加任务
 * @param {QueryKey} queryKey
 * @return {*}
 */
export const useAddTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (data: Partial<Task>) =>
      client("/task/create", {
        method: "POST",
        data,
      }),
    useOptimisticAddConfig(queryKey)
  );
};

/**
 * @description: 删除任务
 * @param {QueryKey} queryKey
 * @return {*}
 */
export const useDeleteTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (data: Partial<Task>) =>
      client(`/task/del`, {
        method: "POST",
        data: { id: data.id },
      }),
    useOptimisticDeleteConfig(queryKey)
  );
};

/**
 * @description: 更新
 * @param {QueryKey} queryKey
 * @return {*}
 */
export const useUpdateTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (data: Partial<Task>) =>
      client(`/task/edit`, {
        method: "POST",
        data,
      }),
    useOptimisticUpdateConfig(queryKey)
  );
};

export const useQueryTaskDetail = (id?: number) => {
  const client = useHttp();
  return useQuery(["task", { id }], () => client(`/task/${id}`), {
    enabled: !!id,
  });
};

export const useSortTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (data: SortParam) =>
      client(`/task/sort`, {
        method: "POST",
        data: {
          fromId: data.fromId,
          toId: data.toId,
          sortType: data.sortType,
          kanbanId: data.kanbanId,
        },
      }),
    useOptimisticSortConfig(queryKey)
  );
};
